<template>
    <view class="certifiedMember">
        <!-- 头像弹窗 -->
        <u-action-sheet :actions="lists" :show="chooseAvaters" @select="editAvater" @close="chooseAvaters=false"></u-action-sheet>

        <u-picker :show="showdizhi" ref="uPicker" :columns="cityList" keyName="title" @confirm="confirm" @change="changeHandler">
        </u-picker>
        <view class="formBox">
            <u--form labelPosition="left" :model="form" ref="form1">
                <u-form-item class=" " label=" " prop="avatar" borderBottom ref="item1">
                    <view class=" avatar">

                        <view class="vh-c avaterBox u-demo-block">
                            <image :src='imgArr' @click="chooseAvater"></image>
                        </view>
                    </view>
                </u-form-item>
                <u-form-item label="姓名" prop="name" borderBottom ref="item1">
                    <u--input v-model="form.name" border="none" placeholder="请输入姓名" @input="changeinput($event,'name')"></u--input>
                </u-form-item>
                <u-form-item label="身份证号" prop="idCard">
                    <u--input v-model="form.idCard" @input="changeinput($event,'idCard')" />
                </u-form-item>
                <u-form-item label="手机号" prop="phone">
                    <u--input v-model="form.phone" @input="changeinput($event,'phone')" />
                </u-form-item>
                <u-form-item label="工龄(年)" prop="serviceLength">
                    <u-number-box integer v-model="form.serviceLength" :min="0" :max="100" @change="valChange"></u-number-box>
                </u-form-item>
                <u-form-item label="擅长技能" prop="skill">
                    <u--textarea v-model="form.skill" @input="changeinput($event,'skill')" />
                </u-form-item>
                <u-form-item label="所在城市" prop="cityName" @click="showdizhi=true">
                    <u--input v-model="form.cityName" :disabled="true" />
                    <u-icon slot="right" name="arrow-right"></u-icon>
                </u-form-item>

                <u-form-item label="案例图片" prop="images">
                    <view class="u-demo-block shigongimgs">
                        <view class="u-demo-block__content">
                            <view class="u-page__upload-item">
                                <!-- :maxCount="2" -->
                                <u-upload :fileList="imagesList" @afterRead="afterRead" @delete="deletePic" name="4" multiple>
                                </u-upload>
                            </view>
                        </view>
                    </view>
                </u-form-item>

            </u--form>
            <u-button type="primary" text="提交" :disabled="disabledbtn" customStyle="margin-top: 50rpx" @click="submit"></u-button>
        </view>
    </view>
</template>

<script>
export default {
    data() {
        return {
            form: {
                name: '',
                serviceLength: 0,
            },
            imgArr: require('../../static/imgs/ren.png'),
            showdizhi: false,

            imagesList: [],
            rules: {
                name: {
                    type: 'string',
                    required: true,
                    message: '请填写姓名',
                    trigger: ['blur', 'change']
                },
                phone: [{
                    type: 'string', required: true, message: '请填写手机号', trigger: ['blur', 'change']
                }, {
                    validator: (rule, value, callback) => {
                        return uni.$u.test.mobile(value);
                    },
                    message: "请填写正确的手机号",
                    trigger: ["change", "blur"],
                }],
                idCard: [{ type: 'string', required: true, message: '请填写身份证号', trigger: ['blur', 'change'] },
                {
                    validator: (rule, value, callback) => {
                        return uni.$u.test.idCard(value);
                    },
                    message: "请填写正确的身份证号",
                    trigger: ["change", "blur"],
                }],
                skill: {
                    type: 'string',
                    required: true,
                    message: '请填写擅长技能',
                    trigger: ["change", "blur"],
                },
                cityName: {
                    type: 'string',
                    required: true,
                    message: '请选择所在城市',
                    trigger: ["change", "blur"],
                },
                avatar: {
                    type: 'string',
                    required: true,
                    message: '请上传头像',
                    trigger: ["change", "blur"],
                },

                // images: [{ required: true, message: '请上传' }],
            },
            cityList: [],
            chooseAvaters: false,
            lists: [  // 操作菜单的列表内容
                {
                    name: '更换头像',
                    color: '',
                    type: 1,
                    fontSize: '28',
                },
                {
                    name: '查看大图',
                    color: '',
                    type: 2,
                    fontSize: '28',
                }
            ],
            disabledbtn: false,
            showdizhi: false,
        }
    },

    onLoad() {
        console.log('onload')
        this.userInfo = this.$store.state.userInfo ? this.$store.state.userInfo : ''
        this.getCity()
        this.getuserinfo()
    },
    //页面显示
    onShow() {
    },
    onReady() {
        // 如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则
        this.$refs.form1.setRules(this.rules)
    },
    methods: {
        getuserinfo() {
            console.log('获取个人信息')
            this.$http.get('/app/user_info/get_user_info/' + this.userInfo.userId).then(val => {
                // this.cityList[0] = val.data
                // this.form=val.data
                this.form.name = val.data.userName
                this.form.avatar = val.data.avatar
                this.form.phone = val.data.phone
                this.form.idCard = val.data.idCard
                this.form.skill = val.data.skill
                this.form.cityName = val.data.cityName
                this.form.serviceLength = val.data.serviceLength
                this.form.cityId = val.data.cityId
                this.form.id = val.data.id
                this.form.images = val.data.imgaes?val.data.imgaes.split(','):''
                this.imgArr = val.data.avatar
                this.imagesList = []
                // this.imagesList=val.data.imgaes.split(',')
                if(val.data.imgaes){

                for (var i in val.data.imgaes.split(',')) {
                    let param = {
                        url: val.data.imgaes.split(',')[i]
                    }
                    this.imagesList.push(param)
                }
                }
                // this.images=val.data.imgaes.split(',')
                console.log(this.imagesList)
                console.log(this.images)

            })
        },
        changeinput(value, machIndex) {
            this.form[machIndex] = value
            console.log(this.form);
            this.$forceUpdate()
        },
        submit() {

            // return
            // 如果有错误，会在catch中返回报错信息数组，校验通过则在then中返回true
            this.$refs.form1.validate().then(res => {
                console.log(this.form)
                let param = JSON.parse(JSON.stringify(this.form))
                param.imgaes = param.images ? param.images.join(',') : ''
                delete param.images

                // param.id = uni.getStorageSync("userInfo").userId
                console.log(param)
                // return

                uni.showLoading({
                    title: '加载中'
                });
                this.disabledbtn = true
                this.$http.put('/promotion/workerInfo', param).then(val => {
                    console.log(val);
                    if (val.code == 200) {
                        uni.showToast({
                            title: val.message,
                            icon: "success",
                            duration: 2000
                        });
                        uni.navigateBack();
                        this.disabledbtn = false
                    }
                    else {
                        uni.showToast({
                            title: val.message,
                            icon: "none",
                            duration: 2000
                        });
                        this.disabledbtn = false
                        uni.hideLoading();
                    }
                }).catch(errors => {
                    this.disabledbtn = false
                    uni.hideLoading();
                    console.log(errors);
                })
            }).catch(errors => {
                console.log(errors)
                uni.$u.toast('请补全信息')
            })
        },
        chooseAvater() {
            console.log(123);
            this.chooseAvaters = true

        },
        editAvater(e) {
            console.log(e)
            if (e.type === 1) {
                this.chooseImage()
            } else {
                this.previewImage()
            }
        },
        chooseImage() {
            let that = this
            console.log('lalala')
            uni.chooseImage({
                count: 1,//限制图片上传数量，封顶9张
                success: (res) => {//拿到图片的返回数据
                    uni.uploadFile({
                        url: that.$base.baseUrl + "sys/common/upload", // 仅为示例，非真实的接口地址
                        filePath: res.tempFilePaths[0],
                        name: 'file',
                        header: {
                            "token": uni.getStorageSync("userInfo").token //token校验
                        },
                        success: (res1) => {
                            console.log('lalall');
                            console.log(res1);

                            this.imgArr = res.tempFilePaths
                            this.chooseAvaters = false
                            this.form.avatar = JSON.parse(res1.data).data
                            this.$forceUpdate()
                            console.log(this.form)
                        }
                    });
                }
            })
        },
        previewImage() {
            uni.previewImage({
                urls: [this.imgArr],//拿头像地址
            })
        },

        // 删除图片
        deletePic(event) {
            this.imagesList.splice(event.index, 1)
            this.form.images.splice(event.index, 1)
        },
        // 新增图片
        async afterRead(event) {
            // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
            let lists = [].concat(event.file)
            let fileListLen = this.imagesList.length
            lists.map((item) => {
                this.imagesList.push({
                    ...item,
                    status: 'uploading',
                    message: '上传中'
                })
            })
            for (let i = 0; i < lists.length; i++) {
                const result = await this.uploadFilePromise(lists[i].url)
                let item = this.imagesList[fileListLen]
                this.imagesList.splice(fileListLen, 1, Object.assign(item, {
                    status: 'success',
                    message: '',
                    url: result
                }))
                fileListLen++
            }
        },
        uploadFilePromise(url) {
            console.log(url)
            let that = this
            return new Promise((resolve, reject) => {
                let a = uni.uploadFile({
                    url: that.$base.baseUrl + "sys/common/upload", // 仅为示例，非真实的接口地址
                    filePath: url,
                    name: 'file',
                    header: {
                        "token": uni.getStorageSync("userInfo").token //token校验
                    },
                    success: (res) => {
                        console.log(res)
                        that.form.images = that.form.images ? that.form.images : []
                        that.form.images.push(JSON.parse(res.data).data)
                        console.log(that.form)
                        resolve(res.data.data)
                    }
                });
            })
        },

        getCity() {
            this.$http.get('/promotion/workerInfo/city_list').then(val => {
                this.cityList[0] = val.data
            })
        },
        //选择地址
        confirm(e) {
            this.showdizhi = false
            this.form.cityName = e.value[0].title
            this.form.cityId = e.value[0].id
            console.log(this.form);
            this.$forceUpdate()

        },
    },
}
</script>


<style lang="scss">
.certifiedMember {
    background-color: #fff;
    min-height: 100vh;
    .rzbj {
        width: 100%;
    }
    .formBox {
        background-color: #fff;
        // border-radius: 30rpx 30rpx 0 0;
        // top: -30rpx;
        position: relative;
        min-height: 100vh;
        background-color: #fff;
        padding: 30rpx 40rpx 40rpx 40rpx;
        .avatar {
            .u-demo-block {
                .u-upload__wrap__preview {
                    border-radius: 50%;
                    box-shadow: 0px 3rpx 8rpx 0rpx rgba(0, 0, 0, 0.2);
                    // border: 6rpx solid #ffffff;
                }
                .u-upload__wrap {
                    display: flex;
                    justify-content: center;
                }
                image {
                    width: 120rpx !important;
                    height: 120rpx !important;
                    border-radius: 50%;
                    box-shadow: 0px 3rpx 8rpx 0rpx rgba(0, 0, 0, 0.2);
                }
                .tip {
                    margin-top: 10rpx;
                    font-size: 22rpx;
                    font-weight: 400;
                    color: #999999;
                    line-height: 37rpx;
                }
            }
        }
        .u-form-item {
            border: none;
        }
        .u-upload__wrap__preview__image,
        .u-upload__button {
            width: 200rpx !important;
            height: 200rpx !important;
        }
        .u-upload__deletable {
            width: 50rpx !important;
            height: 50rpx !important;
            text {
                top: 20rpx !important;
                font-size: 40rpx !important;
            }
        }
        .u-input__content {
            padding: 20rpx;
        }
        .u-border {
            border: none !important;
        }
        .u-line {
            display: none;
        }
        .u-form-item__body__right__message {
            margin-left: 0 !important;
        }
        .u-form-item__body {
            display: block !important;
        }
        .u-input--square,
        .select {
            margin: 0 !important;
            background: #f8f8f8 !important;
            padding: 0 !important;
        }
        .u-form-item__body__left__content__label {
            white-space: nowrap;
            font-size: 36rpx !important;
            font-weight: 600 !important;
            color: #000000 !important;
            line-height: 50rpx !important;
            margin: 20rpx 0 !important;
        }
        .u-input,
        .u-textarea {
            margin-top: 20rpx;
            background: #f8f8f8 !important;
            border-radius: 8rpx;
            border: none;
            // padding: 20rpx !important;
        }

        .u-picker__view__column,
        .u-picker__view {
            height: 40vh !important;
        }
        .shigongimgs {
            margin-bottom: 40rpx;
            .uicon-camera-fill {
                font-size: 60rpx !important;
            }
        }

        .u-number-box__plus,
        .u-number-box__input,
        .u-number-box__minus {
            height: 70rpx !important;
            width: 60rpx !important;
        }
    }
    .avaterBox {
        padding: 40rpx 0;
    }
    .u-picker__view__column,
    .u-picker__view {
        height: 40vh !important;
    }
}
</style>